<?php
class Controller_Storage_Product extends Controller_Abstract
{
	function actionProductWarehouseCreate()
	{
		$this->_view['title'] = '新建';
		$warehouse = Warehouse::find()->asArray()->getAll();
		$this->_view['warehouse'] = $warehouse;
	}
	
	function actionProductWarehouseCreateSave()
	{
		$this->_view['title'] = '新建（保存）';
		$product_basic_number = explode("\n", $_POST['product_number']);
		foreach ($product_basic_number as &$val)
		{
			$val = trim($val);
		}
		unset($val);
		$create_result = Product_Warehouse::create($product_basic_number, $_POST['select_warehouse']);
		if ($create_result['ack'] == SUCCESS)
		{
			return $this->_redirectMessage('保存成功', '正在返回..', url('Storage::Product/ProductManage'), $create_result['ack']);
		}
		if ($create_result['ack'] == PARTIAL_FAILURE)
		{
			return $this->_redirectMessage('保存失败', $create_result['message'], $_SERVER['HTTP_REFERER'], FAILURE);
		}
		else
		{
			return $this->_redirect(url('Storage::Product/ProductManage'));
		}
	}
	function actionMaterialList()
	{
		$this->_view['title'] = '包材列表';
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 0;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 10;
		$url_arr = Helper_BSS_Normal::buildCondition();
		if ($cp == 0 && $ps == 0)
		{
			$material = Product_Material::find()->asArray()->getAll();
			$page = new Helper_BSS_Page(array(), url('Storage::Product/MaterialList', $url_arr));
			$this->_view['page'] = $page->getPage();
			$this->_view['material'] = $material;
		}
		else
		{
			$material = Product_Material::find()->limitPage($cp, $ps);
			$page = new Helper_BSS_Page($material->getPagination(), url('Storage::Product/MaterialList', $url_arr));
			$this->_view['page'] = $page->getPage();
			$this->_view['material'] = $material->asArray()->getAll();
		}
	}
	
	function actionMaterialCreate()
	{
		$this->_view['title'] = '新增包材';
		if (isset($_GET['id']))
		{
			$material = Product_Material::find('id=?', $_GET['id'])->asArray()->getOne();
			if ($material)
			{
				$this->_view['material'] = $material;
			}
		}
	}
	
	function actionMaterialCreateSave()
	{
		$this->_view['title'] = '新增包材（保存）';
		if ($this->_context->isPOST())
		{
			if ($_POST['number'])
			{
				$material_in_db = Product_Material::find('number=?', $_POST['number'])->asArray()->getOne();
				if ($material_in_db)
				{
					return $this->_redirectMessage('包材编号已存在！', '正在返回..', $_SERVER['HTTP_REFERER']);
				}
				$material = new Product_Material();
				$material->number = trim($_POST['number']);
				$material->name = trim($_POST['name']);
				$material->specifications = $_POST['specifications'];
				$material->weight = $_POST['weight'];
				$material->save();
				return $this->_redirectMessage('添加成功', '正在返回..', $_SERVER['HTTP_REFERER'], SUCCESS);
			}
			else
			{
				return $this->_redirect($_SERVER['HTTP_REFERER']);
			}
		}
	}
	
	function actionMaterialEditSave()
	{
		$this->_view['title'] = '编辑包材（保存）';
		if ($this->_context->isPOST())
		{
			$material = Product_Material::find('number=?', $_POST['number'])->getOne();
			$material->number = trim($_POST['number']);
			$material->name = trim($_POST['name']);
			$material->specifications = $_POST['specifications'];
			$material->weight = $_POST['weight'];
			$material->price = $_POST['price'];
			$material->provider = $_POST['provider'];
			$material->save();
			return $this->_redirectMessage('编辑成功', '返回列表', url('Storage::Product/MaterialList'), SUCCESS);
		}
	}
	
	function actionProductShelfPositionCreate()
	{
		$this->_view['title'] = '新建产品架位';
	}
	
	function actionProductShelfPositionCreateSave()
	{
		$this->_view['title'] = '新建产品架位（保存）';
		if (isset($_POST['position_name']))
		{
			$position_name = Q::normalize($_POST['position_name'], "\n");
			foreach ($position_name as $pn)
			{
				if(strpos($pn, ":") === false)
				{
					$product_shelf_position = Product_Shelf_Position::find("position=?", $pn)  -> asArray() -> getOne();
					if(!$product_shelf_position)QDB::getconn()->execute('insert into product_shelf_position (position) value (\'' . $pn . '\')');
				}else{
					$default_warehouse_id = Warehouse::getDefaultWarehouseId();
					$self_position = Q::normalize($pn, ":");
					if(!empty($self_position[0]) && !empty($self_position[1]))
					{
						$product_shelf_position = Product_Shelf_Position::find("position=?", $self_position[1]) -> asArray() -> getOne();
						if(!$product_shelf_position) QDB::getconn()->execute('insert into product_shelf_position (position) value (\'' . $self_position[1] . '\')');
						Product_Warehouse::create($self_position[0], $default_warehouse_id, $self_position[1]);
					}
				}
			}
			return $this->_redirectMessage('操作成功！', '正在返回..', url('Storage::Product/ProductShelfPosition'), SUCCESS);
		}
		else
		{
			return $this->_redirect($SERVER['HTTP_REFERER']);
		}
	}
	
	function actionProductShelfPosition()
	{
		$this->_view['title'] = '产品架位管理';
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 1;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 10;
		$url_arr = Helper_BSS_Normal::buildCondition();
		$result = Product_Shelf_Position::search($url_arr, $cp, $ps, 'product_shelf_position.position asc');
		if ($result['ack'])
		{
			$page = new Helper_BSS_Page($result['pagination'], url('Storage::Product/ProductShelfPosition', $url_arr));
			$this->_view['page'] = $page->getPage();
			$this->_view['product_shelf_position'] = $result['data'];
		}
	}
	
	function actionProductShelfPositionEditSave()
	{
		$this->_view['title'] = '产品架位编辑（ajax保存）';
		$id = $_REQUEST['id'];
		$shelf_position = $_REQUEST['position'];
		QDB::getConn()->execute('update product_shelf_position set position=\'' . $shelf_position . '\' where id=' . $id);
		echo 1;exit;
	}
	
	function actionProductShelfPositionDelete()
	{
		$this->_view['title'] = '产品架位删除';
		if (isset($_GET['id']))
		{
			Product_Shelf_Position::meta()->deleteWhere('id=?', $_GET['id']);
			return $this->_redirectMessage('删除成功', '正在返回..', $_SERVER['HTTP_REFERER'], SUCCESS);
		}
		else
		{
			return $this->_redirect($_SERVER['HTTP_REFERER']);
		}
	}
	
	function actionShelfPositionProduct()
	{
		$this->_view['title'] = '产品架位信息';
		if ($_GET['id'])
		{
			$shelf_position = Product_Shelf_Position::find('id=?', $_GET['id'])->asArray()->getOne();
			if ($shelf_position)
			{
				$product = Product_Warehouse::find('shelf_position like \'%' . $shelf_position['position'] . '%\'')->setColumns('id, storage_number as number, available_quantity as quantity, shelf_position, sales_status, purchase_status')->asArray()->getAll();
				$this->_view['position'] = $shelf_position['position'];
				Helper_BSS_Normal::getProductImgUrl($product);
				$this->_view['product'] = $product;
			}
			else
			{
				echo '没有该架位信息！';exit;
			}
		}
	}
	
	function actionProductManage()
	{
		$this->_view['title'] = '产品包材&架位';
		$warehouse = Warehouse::find()->asArray()->getAll();
		$this->_view['warehouse'] = $warehouse;
		$product_categories = Product_Categories::getCategoriesTree();
		$this->_view['product_categories'] = json_encode($product_categories);
		$material = Product_Material::find()->asArray()->getAll();
		$this->_view['material'] = $material;
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 1;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 10;
		$url_arr = Helper_BSS_Normal::buildCondition();
		$this->_view['url_arr'] = json_encode($url_arr);
		$result = Product_Warehouse::search($url_arr, $cp, $ps, 'product_warehouse.shelf_position desc');
		if ($result['ack'] == SUCCESS)
		{
			$page = new Helper_BSS_Page($result['pagination'], url('Storage::Product/ProductManage', $url_arr));
			$this->_view['page'] = $page->getPage();
			$product = $result['data'];
			Helper_BSS_Normal::getProductImgUrl($product);
			$this->_view['product'] = $product;
			$this->_view['url_arr_json'] = json_encode($url_arr);
		}
		
	}
	
	function actionPositionSave()
	{
		$this->_view['title'] = '产品架位保存（ajax）';
		if (isset($_REQUEST['product_id']) && isset($_REQUEST['position']))
		{
			$check_in_db = Product_Warehouse::find('id=?', $_REQUEST['product_id'])->getOne();
			if ($check_in_db['id'])
			{
				$check_in_db->shelf_position = $_REQUEST['position'];
				$check_in_db->save();
			}
			else
			{
				echo json_encode('不存在该ID=' . $_REQUEST['product_id']);
			}
		}
		else
		{
			echo json_encode('提交信息有误！');
		}
		exit;
	}
	
	function actionDeclaredValueSave()
	{
		$this->_view['title'] = '产品申报价值保存（ajax）';
		if (isset($_REQUEST['product_id']) && isset($_REQUEST['declared_value']))
		{
			$check_in_db = Product_Warehouse::find('id=?', $_REQUEST['product_id'])->getOne();
			if ($check_in_db['id'])
			{
				$check_in_db->declared_value = $_REQUEST['declared_value'];
				$check_in_db->save();
			}
			else
			{
				echo json_encode('不存在该ID=' . $_REQUEST['product_id']);
			}
		}
		else
		{
			echo json_encode('提交信息有误！');
		}
		exit;
	}
	
	function actionProductFeatureSave()
	{
		$this->_view['title'] = '产品特点保存（ajax）';
		if (isset($_REQUEST['product_id']) && isset($_REQUEST['product_feature']))
		{
			$check_in_db = Product_Warehouse::find('id=?', $_REQUEST['product_id'])->getOne();
			if ($check_in_db['id'])
			{
				$check_in_db->product_feature = $_REQUEST['product_feature'];
				$check_in_db->save();
			}
			else
			{
				echo json_encode('不存在该ID=' . $_REQUEST['product_id']);
			}
		}
		else
		{
			echo json_encode('提交信息有误！');
		}
		exit;
	}
	
	function actionProductManageSave()
	{
		$this->_view['title'] = '产品包装材料保存（ajax）';
		if (isset($_REQUEST['product_id']) && isset($_REQUEST['material_id']))
		{
			$check_in_db = Product_Warehouse::find('id=?', $_REQUEST['product_id'])->getOne();
			if ($check_in_db['id'])
			{
				$check_in_db->product_material_id = $_REQUEST['material_id'];
				$check_in_db->save();
			}
			else
			{
				echo json_encode('不存在该ID=' . $_REQUEST['product_id']);
			}
		}
		else
		{
			echo json_encode('提交信息有误！');
		}
		exit;
	}
	
	function actionProductWarehouseTagSave()
	{
		$this->_view['title'] = '产品标签贴保存（ajax）';
		if (isset($_REQUEST['product_id']) && isset($_REQUEST['tag']))
		{
			$check_in_db = Product_Warehouse::find('id=?', $_REQUEST['product_id'])->getOne();
			if ($check_in_db['id'])
			{
				$check_in_db->tag = $_REQUEST['tag'];
				$check_in_db->save();
			}
			else
			{
				echo json_encode('不存在该ID=' . $_REQUEST['product_id']);
			}
		}
		else
		{
			echo json_encode('提交信息有误！');
		}
		exit;
	}
	
	function actionPrintProductBarcode()
	{
		$this->_view['title'] = '打印产品条形码';
		if ($_POST['print_style'] == 'by_check')
		{
			$where = 'product_warehouse.id in (' . implode(',', json_decode($_POST['ids'])) . ')';
		}
		if ($_POST['print_style'] == 'by_search')
		{
			$url_arr = json_decode($_POST['url_arr'], true);
			$where = Product_Warehouse::buildSearchWhere($url_arr);
		}
		if ($_POST['quantity'] == 'quantity')
		{
			$product = Product_Warehouse::find($where)
				->joinLeft('product_material', '', 'product_material.id=product_warehouse.product_material_id')
				->joinLeft('product_basic', '', 'product_basic.id=product_warehouse.product_basic_id')
				->order('shelf_position desc')->setColumns('product_basic.number, product_warehouse.actual_quantity as quantity, product_warehouse.storage_number, product_warehouse.shelf_position, product_warehouse.product_feature, product_material.number as material_number')
				->asArray()->getAll();
			foreach ($product as $k => $p)
			{
				if (empty($p['quantity']))
				{
					unset($product[$k]);
				}
			}
		}
		else
		{
			$product = Product_Warehouse::find($where)
				->joinLeft('product_material', '', 'product_material.id=product_warehouse.product_material_id')
				->joinLeft('product_basic', '', 'product_basic.id=product_warehouse.product_basic_id')
				->order('shelf_position desc')->setColumns('product_basic.number, product_warehouse.storage_number, product_warehouse.storage_title, product_warehouse.shelf_position, product_warehouse.product_feature, product_material.number as material_number')->asArray()->getAll();
			foreach ($product as $k => $p)
			{
				$product[$k]['quantity'] = $_POST['quantity'];
			}
		}
		if (!empty($_POST['warehouse_type']) && $_POST['warehouse_type'] == Q::ini('custom_flag/warehouse_type/baozhou/value'))
		{
			OLM_Barcode::productNumber($product);
		}
		elseif (!empty($_POST['warehouse_type']) && $_POST['warehouse_type'] == Q::ini('custom_flag/warehouse_type/amazon/value'))
		{
			OLM_Barcode::productNumberFBA($product);
		}
		else
		{
			return $this->_redirectMessage('提交信息有误', '请检查提交地址是否错误！', $_SERVER['HTTP_REFERER'], FAILURE);
		}
		exit;
	}
	
	function actionProductInfoAjax()
	{
		$this->_view['title'] = '产品信息请求ajax';
		$default_warehouse_id = Warehouse::getDefaultWarehouseId();
		$product_basic = Product_Warehouse::search(array('number_or_name' => $_REQUEST['q'], 'warehouse_id' => $default_warehouse_id), 0, 10);
		$result = array();
		foreach ($product_basic['data'] as $pb)
		{
			$result[] = array(
					0 => $pb['number'] . ' ' . $pb['product_basic_name'],
					'id' => $pb['product_basic_id'],
					'number' => $pb['number'],
					'purchase_price' => $pb['purchase_price'],
					'cost_price' => $pb['last_purchase_price'],
					'preferred_provider_id' => $pb['preferred_provider_id'],
					'preferred_provider_name' => $pb['preferred_provider_name'],
					'weekly_sales' => $pb['product_basic_weekly_sales'],
					'monthly_sales' => $pb['product_basic_monthly_sales'],
			);
		}
		echo json_encode($result);
		exit;
	}
	
	function actionProductIO()
	{
		$this->_view['title'] = '产品出入库查询';
		$this->_view['warehouse'] = Warehouse::find()->asArray()->getAll();
		if (isset($_GET['is_search']) && isset($_GET['product_number']))
		{
			$condition = Helper_BSS_Normal::buildCondition();
			$where = '1';
			if ( ! empty($condition['begin_time']))
			{
				$where .= ' and inventory_log.time>=\'' . $condition['begin_time'] . '\'';
			}
			if ( ! empty($condition['end_time']))
			{
				$where .= ' and inventory_log.time<=\'' . $condition['end_time'] . ' 23:59:59\'';
			}
			$product_basic = Product_Basic::find('number=?', $condition['product_number'])->asArray()->getOne();
			if ($product_basic)
			{
				$product_warehouse = Product_Warehouse::find('product_basic_id=? and warehouse_id=?', $product_basic['id'], $condition['warehouse_id'])
					->joinLeft('warehouse', 'name as warehouse_name', 'warehouse.id=product_warehouse.warehouse_id')
					->asArray()->getOne();
				if ($product_warehouse)
				{
					$log = Inventory_Log::find('product_basic_id=? and warehouse_id=? and ' . $where, $product_basic['id'], $condition['warehouse_id'])
						->joinLeft('user', 'name as user_name', 'user.id=inventory_log.user_id')
						->asArray()->getAll();
					$this->_view['product_basic'] = $product_basic;
					$this->_view['product_warehouse'] = $product_warehouse;
					$this->_view['log'] = $log;
				}
			}
		}
	}
	
	function actionShopList()
	{
		$this->_view['title'] = '感谢卡号列表';
		$shop = Shop::getActiveShop();
		if (! empty($_GET['platform']))
		{
			$shop = Shop::getPlatformShopToArray($_GET['platform']);
		}
		$this->_view['shop'] = $shop;
	}
	
	function actionShopGiftCardSave()
	{
		$this->_view['title'] = '感谢卡号保存（ajax）';
		$id = $_GET['id'];
		$gift_card = $_GET['gift_card'];
		if (isset($id) && isset($gift_card))
		{
			if (is_numeric($gift_card) && $gift_card >= 0 && $gift_card <= 30)
			{
				QDB::getConn()->execute('update shop set gift_card=' . $gift_card . ' where id = ' . $id);
				echo 0;exit;
			}
			else
			{
				echo $id;exit;
			}
		}
	}
	
	function actionExportInventoryByChecked()
	{
		$this->_view['title'] = '按勾选导出盘点表';
		set_time_limit(300);
		if ($this->_context->isPOST())
		{
			$product = Product_Basic::find("product_warehouse.id in ({$_POST['export_ids']})")
				->joinLeft('product_warehouse', 'actual_quantity, shelf_position', 'product_warehouse.product_basic_id=product_basic.id')
				->asArray()->getAll();
			include Q::ini('custom_system/lib_dir').'PHPExcel.php';
			$phpexcel = new PHPExcel();
			$phpexcel->getProperties()->setCreator(Q::ini('custom_system/system_name') . Q::ini('custom_system/version'));
			$phpexcel->getProperties()->setLastModifiedBy(Q::ini('custom_system/system_name') . Q::ini('custom_system/version'));
			$phpexcel->getProperties()->setTitle("产品盘点表");
			$phpexcel->getProperties()->setSubject("产品盘点表");
			$phpexcel->getProperties()->setDescription("产品盘点表-运营支撑系统");
			$phpexcel->getProperties()->setKeywords("产品盘点表");
			$phpexcel->getProperties()->setCategory("产品盘点表");
			$phpexcel->setActiveSheetIndex(0);
			$phpexcel->getActiveSheet()->setTitle("产品盘点表");
			$phpexcel->getActiveSheet()->setCellValue('A1', "产品编号");
			$phpexcel->getActiveSheet()->setCellValue('B1', "产品名称");
			$phpexcel->getActiveSheet()->setCellValue('C1', "帐存数");
			$phpexcel->getActiveSheet()->setCellValue('D1', "盘点数");
			$phpexcel->getActiveSheet()->setCellValue('E1', "架位");
			$phpexcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('B1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('C1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('D1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('E1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$phpexcel->getActiveSheet()->getStyle('B1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$phpexcel->getActiveSheet()->getStyle('C1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$phpexcel->getActiveSheet()->getStyle('D1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$phpexcel->getActiveSheet()->getStyle('E1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$i = 2;
			foreach ($product as $p)
			{
				$phpexcel->getActiveSheet()->getCell('A'.$i)->setValueExplicit($p['number'], PHPExcel_Cell_DataType::TYPE_STRING);
				$phpexcel->getActiveSheet()->setCellValue('B'.$i, $p['name']);
				$phpexcel->getActiveSheet()->setCellValue('C'.$i, $p['actual_quantity']);
				$phpexcel->getActiveSheet()->setCellValue('D'.$i, '');
				$phpexcel->getActiveSheet()->setCellValue('E'.$i, $p['shelf_position']);
				$i++;
			}
			$outputFileName = "ExportInventoryByChecked.xls";
			$objWriter = new PHPExcel_Writer_Excel5($phpexcel);
			header("Content-Type: application/vnd.ms-execl");
			header("Content-Type: application/octet-stream");
			header("Content-Type: application/download");
			header('Content-Disposition:inline;filename="'.$outputFileName.'"');
			header("Content-Transfer-Encoding: binary");
			header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
			header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
			header("Pragma: no-cache");
			$objWriter->save('php://output');
			exit;
		}
	}
	
	function actionExportInventoryBySearch()
	{
		$this->_view['title'] = '按搜索导出盘点表';
		set_time_limit(300);
		$url_arr = json_decode($_REQUEST['url_arr_json'], true);
		if ($url_arr)
		{
			$where = Product_Warehouse::buildSearchWhere($url_arr);
			$product = Product_Basic::find($where)
				->joinLeft('product_warehouse', 'actual_quantity, shelf_position', 'product_warehouse.product_basic_id=product_basic.id')
				->asArray()->getAll();
			include Q::ini('custom_system/lib_dir').'PHPExcel.php';
			$phpexcel = new PHPExcel();
			$phpexcel->getProperties()->setCreator(Q::ini('custom_system/system_name') . Q::ini('custom_system/version'));
			$phpexcel->getProperties()->setLastModifiedBy(Q::ini('custom_system/system_name') . Q::ini('custom_system/version'));
			$phpexcel->getProperties()->setTitle("产品盘点表");
			$phpexcel->getProperties()->setSubject("产品盘点表");
			$phpexcel->getProperties()->setDescription("产品盘点表-运营支撑系统");
			$phpexcel->getProperties()->setKeywords("产品盘点表");
			$phpexcel->getProperties()->setCategory("产品盘点表");
			$phpexcel->setActiveSheetIndex(0);
			$phpexcel->getActiveSheet()->setTitle("产品盘点表");
			$phpexcel->getActiveSheet()->setCellValue('A1', "产品编号");
			$phpexcel->getActiveSheet()->setCellValue('B1', "产品名称");
			$phpexcel->getActiveSheet()->setCellValue('C1', "帐存数");
			$phpexcel->getActiveSheet()->setCellValue('D1', "盘点数");
			$phpexcel->getActiveSheet()->setCellValue('E1', "架位");
			$phpexcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('B1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('C1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('D1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('E1')->getFont()->setBold(true);
			$phpexcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$phpexcel->getActiveSheet()->getStyle('B1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$phpexcel->getActiveSheet()->getStyle('C1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$phpexcel->getActiveSheet()->getStyle('D1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$phpexcel->getActiveSheet()->getStyle('E1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
			$i = 2;
			foreach ($product as $p)
			{
				$phpexcel->getActiveSheet()->getCell('A'.$i)->setValueExplicit($p['number'], PHPExcel_Cell_DataType::TYPE_STRING);
				$phpexcel->getActiveSheet()->setCellValue('B'.$i, $p['name']);
				$phpexcel->getActiveSheet()->setCellValue('C'.$i, $p['actual_quantity']);
				$phpexcel->getActiveSheet()->setCellValue('D'.$i, '');
				$phpexcel->getActiveSheet()->setCellValue('E'.$i, $p['shelf_position']);
				$i++;
			}
			$outputFileName = "ExportInventoryBySearch.xls";
			$objWriter = new PHPExcel_Writer_Excel5($phpexcel);
			header("Content-Type: application/vnd.ms-execl");
			header("Content-Type: application/octet-stream");
			header("Content-Type: application/download");
			header('Content-Disposition:inline;filename="'.$outputFileName.'"');
			header("Content-Transfer-Encoding: binary");
			header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
			header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
			header("Pragma: no-cache");
			$objWriter->save('php://output');
			exit;
		}
	}
	
	function actionStockCompare()
	{
		$this->_view['title'] = '库存对比';
		$this->_view['warehouse'] = Warehouse::getActiveWarehouse();
		if (isset($_POST['is_search']))
		{
			if (empty($_POST['product_data']))
			{
				return $this->_redirectMessage('查询失败', '请填写库存对比产品信息', $_SERVER['HTTP_REFERER'], FAILURE);
			}
			else
			{
				$product_data = Q::normalize($_POST['product_data'], "\n");
				$item = $message = array();
				foreach ($product_data as $pd)
				{
					$temp = Q::normalize($pd, ',');
					$temp[0] = str_pad($temp[0], 6, 0, STR_PAD_LEFT);
					if (array_key_exists($temp[0], $item))
					{
						$item[$temp[0]]['quantity'] += $temp[1];
					}
					else
					{
						$item[$temp[0]]['quantity'] = $temp[1];
					}
				}
				foreach ($item as $k => $i)
				{
					$check_in_db = Product_Basic::find('number=?', $k)->asArray()->getOne();
					if ($check_in_db)
					{
						$warehouse = Product_Warehouse::find('product_basic_id=? and warehouse_id=?', $check_in_db['id'],$_POST['warehouse_id'])->asArray()->getOne();
						if( ! $warehouse)
						{
							$message[$k]['message'] = '仓库中不存在该产品';
							$message[$k]['quantity'] = $i['quantity'];
							$message[$k]['actual_quantity'] = '-';
							$message[$k]['balance'] = '-';
						}
						else
						{
							if ($i['quantity'] < 0)
							{
								$message[$k]['message'] = '产品实际库存不能为负数';
								$message[$k]['quantity'] = $i['quantity'];
								$message[$k]['actual_quantity'] = $warehouse['actual_quantity'];
								$message[$k]['balance'] = '+' . ($warehouse['actual_quantity'] - $i['quantity']);
							}
							if ($i['quantity'] >= 0 && $i['quantity'] != $warehouse['actual_quantity'])
							{
								$message[$k]['message'] = '填写的实际库存与仓库实际库存不符';
								$message[$k]['quantity'] = $i['quantity'];
								$message[$k]['actual_quantity'] = $warehouse['actual_quantity'];
								$message[$k]['balance'] = ($warehouse['actual_quantity'] - $i['quantity']);
								if ($message[$k]['balance'] > 0)
								{
									$message[$k]['balance'] = '+' . $message[$k]['balance'];
								}
							}
						}
					}
					else
					{
						$message[$k]['message'] = '不存在该产品';
						$message[$k]['quantity'] = $i['quantity'];
						$message[$k]['actual_quantity'] = '-';
						$message[$k]['balance'] = '-';
					}
				}
				if ($message)
				{
					$this->_view['message'] = $message;
				}
			}
		}
	}
}